import { syncSetTimeout, sendMessage, getMessage } from "../../global/tools.js";

export default class AiccyunHandler {
    static count = 0;
    constructor(webController) {
        AiccyunHandler.count++;
        if (AiccyunHandler.count >= 2) {
            alert("collectionPlugin: \nError: AiccyunHandler.count >= 2，即将刷新页面。");
            location.reload(true);
        } 
        this.webController = webController;
        this.config = {
            phoneState: {
                old:  "未知",
                now: "未知"
            }
        };
        // 监听事件
        {
            this.eventListenersFn = {
                dblclick: {
                    title: "dblclick",
                    fn: async e => {
                        if (e.target.className === "mobile" && /^1[3-9]\d{9}$/.test(e.target.innerText)) {
                            this.makeCall(e.target.innerText);
                        }
                        if (e.target.className === "relation" && e.target.innerText.length >= 2 && e.target.innerText.length <= 3) {
                            this.hangUp();
                        }
                    }
                }
            };
            // 开始监听相关事件
            for (const key in this.eventListenersFn) {
                this.webController.document().addEventListener(this.eventListenersFn[key].title, this.eventListenersFn[key].fn, this.eventListenersFn[key].capture ? true : false);
            }
        }
        this.init();
    }
    init() {
        // 添加通话状态显示
        {
            jQuery("ul.list").append(`<li style="color: white; margin-left: 20px; font-size: 18px;"><label>当前状态: </label><span id="collectionPlugin-auto-phoneState">未知</span></li>`); 
        }   
        getMessage("anmi_auto", message => {
            switch (message.title) {
                case "phoneStateChange":
                    this.config.phoneState = message.data.phoneState;
                    this.phoneStateHandler();
                    // this.config.phoneBarElement = message.data.phoneBarElement;
                    break;
                default:
                    break;
            }
        });
    }
    phoneStateHandler() {
        jQuery("#collectionPlugin-auto-phoneState").text(this.config.phoneState.now);
        if (this.config.phoneState.now === "通话中") {
            jQuery("#collectionPlugin-auto-phoneState").css("color", "#06fb1b");
            this.shakeElement(document.getElementById("main-layout-con"));
        } else {
            jQuery("#collectionPlugin-auto-phoneState").css("color", "#fff");
        }
    }
    makeCall(phoneNumber) {
        // 如果传参为5~18位纯数字才发送消息进行呼叫
        if(/^\d{5,18}$/.test(phoneNumber)) {
            sendMessage({
                from: "anmi_aiccyunHandler",
                to: "aiccyun_call",
                toUrl: "https://*.aigcyun.cn/",
                title: "call",
                data: phoneNumber
            });
        }
    }
    hangUp() {
        sendMessage({
            from: "anmi_aiccyunHandler",
            to: "aiccyun_call",
            toUrl: "https://*.aigcyun.cn/",
            title: "hangUp",
            data: ""
        });
    }
    //窗口抖动
    shakeElement(element) {
        if (!element || !(element instanceof Element)) {
            console.error('Invalid element provided.');
            return;
        }
    
        // 定义震动次数和位移幅度
        const duration = 500; // 总共震动时间（毫秒）
        const maxOffset = 5;  // 最大偏移量（像素）
    
        let startTime = null;
    
        function animate(timestamp) {
            if (!startTime) startTime = timestamp;
            const elapsed = timestamp - startTime;
    
            if (elapsed < duration) {
                const offsetX = Math.random() * maxOffset * 2 - maxOffset;
                const offsetY = Math.random() * maxOffset * 2 - maxOffset;
                element.style.transform = `translate(${offsetX}px, ${offsetY}px)`;
                requestAnimationFrame(animate);
            } else {
                // 恢复原始位置
                element.style.transform = '';
            }
        }
        requestAnimationFrame(animate);
    }
}